from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
#为了缓存地址,减轻sql的压力,把不变的数据变成缓存数据,然后整个页面报错到redis里,下次直接映射redis的数据
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from address.models import area, Address
from address.serializers import AreaSerializer, ParentSerializer, AddressSerializers
from utils.permission import auto_user, update_auto_user, destroy_auto_user


class AreaViewSet(CacheResponseMixin,ModelViewSet):
    queryset = area.objects.all()
    serializer_class = AreaSerializer
    def get_queryset(self):
        if self.action =='list':
            return area.objects.filter(parent_id=None)
        return self.queryset

    def get_serializer_class(self):
        if self.action == 'retrieve' or self.action == 'list':
            # 省份
            return ParentSerializer
        else:
            return AreaSerializer
    @action(methods=['get'],detail=True)
    def get_city(self,request,pk):
        try:
            city = area.objects.get(id=pk).area_set
        except:
            return Response({
                'status': status.HTTP_404_NOT_FOUND,
                'msg': '无法查询到该文章的评论信息！'
            })
        serializers = self.get_serializer(city,many=True)
        return Response({
            'msg': 'ok',
            'data':serializers.data
        })
class AddressViews(ModelViewSet):
    # 为什么不直接怎么写，因为这个模型的三个字段共同关联了一个表，不建议怎么写
    # queryset = Address.objects.filter(is_delete=False)
    serializer_class = AddressSerializers
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        # 此处这样的写法要在路由哪里加上一个basename='模型表的小写'
        # 这个和queryset的差别就是有没有basename，用qyeryset就不用加basename
        return self.request.user.address_set.filter(is_delete=False)

    @auto_user
    def create(self, request, *args, **kwargs):
        if request.POST.get('is_check') == '0':
            data = self.get_queryset()
            for i in data:
                i.is_check = 1
                i.save()
        max_count = 5
        if self.get_queryset().count() >= max_count:
            return Response({
                'status':status.HTTP_400_BAD_REQUEST,
                'msg':f'收货地址数量超过{max_count}条上限'
            })
        ModelViewSet.create(self, request, *args, **kwargs)
        serializer = AddressSerializers(self.get_queryset(),many=True)
        return Response({
            'msg':'数据添加成功',
            'status':status.HTTP_202_ACCEPTED,
            'data':serializer.data
        })

    @update_auto_user
    def update(self, request, *args, **kwargs):
        if request.data['is_check'] == 0:
            data = self.get_queryset()
            for i in data:
                i.is_check = 1
                i.save()
        ModelViewSet.update(self, request, *args, **kwargs)
        serializer = AddressSerializers(self.get_queryset(),many=True)
        return Response({
            'msg': '数据修改成功',
            'status': status.HTTP_202_ACCEPTED,
            'data': serializer.data
        })

    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        ModelViewSet.destroy(self, request, *args, **kwargs)
        serializer = AddressSerializers(self.get_queryset(), many=True)
        return Response({
            'msg': '数据删除成功',
            'status': status.HTTP_200_OK,
            'data': serializer.data
        })


